package com.xingxing.sqlSession;

import com.mysql.cj.util.StringUtils;
import com.xingxing.pojo.Configuration;
import com.xingxing.pojo.MapperdStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @program: IPersistence_test
 * @description:
 * @author: xinghaozhao
 * @create: 2020-08-22
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... parms) throws Exception {
        //调用SimpleExecutor中的query方法
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperdStatement mapperdStatement = configuration.getMapperdStatementMap().get(statementId);
        List<Object> list = simpleExecutor.query(configuration, mapperdStatement, parms);

        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... parms) throws Exception {
        List<Object> objects = selectList(statementId, parms);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("返回结果为空或者返回结果过多");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理为Dao层接口生成代理对象 并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 底层还是去调用JDBC代码，根据不同情况调用selectList 或 selectOne

                // 准备参数 1：statementId：sql语句的唯一标识，由namespace.id == 接口全限定名.方法名
                // 方法名：findAll
                String methodName = method.getName();

                // 接口全限定名
                String className = method.getDeclaringClass().getName();

                // 拼接参数statementId
                String statementId = className + "." + methodName;

                // 准备参数 2：params：args
                // 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                // 判断返回值是否进行了泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> list = selectList(statementId,args);
                    return list;
                }
                return selectOne(statementId, args);

            }
        });
        return (T) proxyInstance;
    }
}
